package logic

import (
	"context"
	"fmt"
	"product/model/mysql"

	"product/goodrpc/goodrpc"
	"product/goodrpc/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
)

type ListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ListLogic {
	return &ListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *ListLogic) List(in *goodrpc.ListRequest) (*goodrpc.ListResponse, error) {
	// todo: add your logic here and delete this line
	var goods []mysql.Good
	page := in.Page
	if page <= 0 {
		page = 1
	}
	pageSize := in.Size
	switch {
	case pageSize > 100:
		pageSize = 100
	case pageSize <= 0:
		pageSize = 5
	}
	offset := (page - 1) * pageSize
	err := mysql.DB.Debug().Offset(int(offset)).Limit(int(pageSize)).Order("price desc").Find(&goods).Error
	if err != nil {
		return nil, fmt.Errorf("查询展示失败")
	}
	var lists []*goodrpc.GoodList
	for _, good := range goods {
		list := goodrpc.GoodList{
			Id:       int64(good.ID),
			Userid:   int64(good.Userid),
			Name:     good.Name,
			Image:    good.Image,
			Quantity: int64(good.Quantity),
			Price:    int64(good.Price),
			Page:     in.Page,
			Size:     in.Size,
		}
		lists = append(lists, &list)
	}
	return &goodrpc.ListResponse{List: lists}, nil
}
